<template>
  <el-container>
    <el-main>
      <el-form
        ref="articleForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <div
          style="
            width: 100%;
            display: flex;
            align-items: flex-end;
            border-bottom: 1px #eee solid;
            margin-bottom: 20px;
          "
        >
          <span style="font-size: 18px; color: #409eff; margin: 10px 0"
            >基本信息</span
          >
        </div>
        <el-form-item label="主标题" prop="title">
          <el-col :span="5">
            <el-input v-model="form.title" style="width: 300px" />
          </el-col>
        </el-form-item>
        <el-form-item label="媒体类型" prop="mediaType">
          <el-select
            v-model="form.mediaType"
            style="width: 248px"
            @change="changges"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-col :span="5">
            <el-cascader
              v-model="value"
              :options="articleCategory"
              :props="props"
              ref="cascaderDept"
              style="width: 300px"
            >
            </el-cascader>
          </el-col>
        </el-form-item>
        <el-form-item
          :key="Math.random()"
          label="位置标签"
          style="margin-top: 20px"
        >
          <el-select
            v-model="tagData"
            multiple
            placeholder="请选择"
            style="width: 248px"
          >
            <el-option
              v-for="item in tagForm"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否草稿">
          <el-radio-group v-model="form.isDraft">
            <el-radio :label="false">已发布</el-radio>
            <el-radio :label="true">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文章类型">
          <el-radio-group v-model="form.linkType">
            <el-radio :label="0">图文介绍</el-radio>
            <el-radio :label="1">链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <div
          class="photo-content"
          style="margin-top: 10px"
          v-if="form.mediaType == 0"
        >
          <div style="margin-top: 20px" class="photo-content-span">
            <span style="font-size: 18px; color: #409eff">轮播图</span>
          </div>
          <el-col>
            <multi-upload
              :key="times"
              v-model="form.articleMeta.images"
            ></multi-upload>
          </el-col>
        </div>
        <template v-if="form.linkType">
          <el-form-item label="链接" prop="author">
            <el-input v-model="form.linkAddress" style="width: 320px" />
          </el-form-item>
        </template>
        <template v-else>

          <div
            v-if="form.mediaType == 0"
            style="
            width: 100%;
            display: flex;
            flex-direction: column;
            margin-bottom: 10px;
            margin-left: 15px;
            margin-top: 20px;
          "
          >
          <span style="font-size: 18px; color: #409eff; margin: 10px 0"
          >笔记内容</span
          >
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="form.content"
              style="width: 25%; margin-left: 10px; margin-top: 15px"
            >
            </el-input>
          </div>

          <div
            v-if="form.mediaType == 1"
            class="video-content"
            style="margin-left: 14px; margin-bottom: 20px"
          >
            <el-form-item label="视频介绍">
              <video-upload v-model="form.articleMeta.video" />
            </el-form-item>
          </div>

        </template>


      </el-form>
      <el-button
        class="el-button—class"
        type="primary"
        :loading="clicked"
        @click="updateArticle('articleForm')"
      >
        &nbsp&nbsp完 成&nbsp&nbsp
      </el-button>
      <category-dialog
        ref="categoryDialog"
        request="articleCategory"
        @confirm="categoryDialogConfirm"
      />
    </el-main>
  </el-container>
</template>
<style scoped>
.el-button—class {
  margin-top: 20px;
}
/deep/ .el-upload--picture-card {
  width: 50px !important;
  height: 50px !important;
  line-height: 50px !important;
  text-align: center;
}
.photo-content {
  width: 100%;
  /* display: flex;
  align-items: flex-end; */
  margin-left: 15px;
  margin-bottom: 10px;
}
.photo-content .photo-content-span {
  margin-bottom: 20px;
}
.photo-content {
  width: 100%;
  /* display: flex;
  align-items: flex-end; */
  margin-left: 15px;
  margin-bottom: 10px;
}
.el-button—class {
  margin-top: 20px;
  margin-left: 14px;
}
/deep/.el-textarea__inner {
  height: 150px;
}
/deep/.el-col-24 {
  margin-bottom: 30px;
}
/deep/.el-upload__tip {
  display: none;
}
/deep/.el-select--medium {
  width: 300px !important;
}
</style>
<script>
import { list as classlist } from "@/api/articleCategory";
import VideoUpload from "@/components/Upload/videoUpload";
import MultiUpload from "@/components/Upload/multiUpload";
import { EventBus } from "@/api/eventBus";
import utils from "../../utils/utils.js";
import { update, find } from "@/api/article";
import { list as tagList } from "@/api/tag";
import Tinymce from "@/components/Tinymce";
import CategoryDialog from "@/components/CategoryDialog";
import SingleUpload from "@/components/Upload/singleUpload";
export default {
  name: "note-edit",
  filters: {},
  components: {
    Tinymce,
    CategoryDialog,
    SingleUpload,
    MultiUpload,
    VideoUpload,
  },
  data() {
    return {
      value: [],
      props: {
        value: "id",
        label: "name",
        children: "childrens",
      },
      options: [
        {
          value: 0,
          label: "图文",
        },
        {
          value: 1,
          label: "视频",
        },
      ],
      singleUploadTitle: "750*900",
      clicked: false, // 按钮防双击
      categoryName: "",
      articleCategory: [],
      form: {
        //  articleCategoryName:'',
        mediaType: "",
        isDraft: "",
        linkType: 0,
        linkAddress: "",
        id: "",
        title: "",
        subTitle: "",
        thumbnail: "",
        content: "",
        articleCategoryId: "",
        articleType: 2,
        authority: 0,
        articleMeta: {
          address: "",
          time: "",
          images: [],
          video: "",
        },
        price: 0,
      },
      status: 0,
      subscribe: false,
      tagData: [],
      tagForm: [],
      times: null,
      rules: {
        title: [
          { required: true, message: "请输入主标题", trigger: "blur" },

        ],
      },
    };
  },
  watch: {
    // 路由地址不变的情况下,如果id变化则重新获取数据
    $route(newVal, oldVal) {
      console.log(newVal);
      if (newVal.name == "note-edit" && newVal.query.id != this.id) {
        this.getData();
      }
    },
  },
  created() {
    this.getData();
    this.tagList();
    this.getclassification();
  },
  // watch: {
  //   // 只要路由发生变化就重新获取数据
  //   $route(newVal, val) {
  //     if (newVal.query.id !== undefined) {
  //       this.getData();
  //     }
  //   },
  // },
  methods: {
    changges(val) {
      console.log(val);
    },

    changeArticle(val, index) {
      console.log(val);
      console.log(this.value);
      if (val.childrens.length == 0) {
        this.$refs.cascaderDept.dropDownVisible = false;
        // this..
      }
      // console.log(index);
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].childrens.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].childrens = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].childrens);
        }
      }
      return data;
    },

    getclassification() {
      let params = new URLSearchParams();

      params.append("articleType", this.form.articleType);
      classlist(params).then((res) => {
        console.log(res);
        this.articleCategory = this.getTreeData(res.data);
        console.log(this.articleCategory);
      });
    },

    getData() {
      var _this = this;
      _this.times = new Date().getSeconds();
      console.log(_this.times);
      _this.form.id = this.$route.query.id;
      find(this.$route.query.id)
        .then((response) => {
          console.log(response);
          _this.form.title = response.data.article.title;
          _this.form.mediaType = response.data.article.mediaType;
          _this.form.subTitle = response.data.article.subTitle;
          _this.form.thumbnail = response.data.article.thumbnail;
          _this.form.content = response.data.article.content;
          _this.form.articleCategoryId = response.data.article.articleCategory;
          _this.form.articleMeta.address =
            response.data.article.articleMeta.address;
          _this.form.articleMeta.time = response.data.article.articleMeta.time;
          _this.categoryName = response.data.article.articleCategoryName;
          _this.form.price = response.data.article.price;
          _this.form.isDraft = response.data.article.isDraft;
          _this.form.linkType = response.data.article.linkType;
          _this.form.linkAddress = response.data.article.linkAddress;
          _this.form.articleMeta.images =
            response.data.article.articleMeta.images;
          _this.form.articleMeta.veido =
            response.data.article.articleMeta.veido;
          _this.tagData = response.data.tags;

          // _this.form.articleCategory = response.data.article.articleCategory;
          _this.value = response.data.article.articleCategoryId;
          response.data.tags.forEach(function (item, index) {
            _this.tagData[index] = item.id;
          });
        })
        .catch((error) => {});
    },
    dialogShow() {
      console.log("点击了");
      this.$refs.categoryDialog.show();
    },
    categoryDialogConfirm(val) {
      this.form.articleCategoryId = val.id;
      this.categoryName = val.name;
    },
    tagList() {
      var _this = this;
      let params = new URLSearchParams();
      params.append("pageNum", 1);
      params.append("pageSize", 20);
      params.append("type", 0);
      tagList(params)
        .then((response) => {
          console.log(response);
          _this.tagForm = response.data.data;
        })
        .catch((error) => {
          console.log("error!!");
        });
    },
    updateArticle(form) {
      const _this = this;
      this.$refs[form].validate((valid) => {
        if (valid) {
          // 校验表单
          _this.clicked = true;
          let params = new URLSearchParams();
          _this.tagData.forEach(function (item) {
            params.append("tagIds", item);
          });
        console.log(_this.value);
          if(_this.value!=undefined){
            _this.form.articleCategoryId = _this.value[_this.value.length - 1];
          }else{
             _this.form.articleCategoryId=''
          }

          update(_this.form, params)
            .then((response) => {
              console.log(response);
              _this.clicked = false;
              if (response.type == "success") {
                EventBus.$emit("note-edit", response.data);
                _this.$store
                  .dispatch("tagsView/delView", _this.$route)
                  .then(({ visitedViews }) => {
                    _this.$router.push({
                      path: "/note/list",
                    });
                  }); // 关闭当前tab回到列表
              } else {
                _this.$message({
                  message: response.content,
                  offset: 120,
                  center: true,
                });
              }
            })
            .catch((error) => {
              _this.clicked = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>
